package com.mzy;

import com.sun.org.apache.xerces.internal.impl.dv.xs.DoubleDV;

import java.util.jar.JarEntry;

public class ReverseList {

    public static class Node {
        public int value;
        public Node next;

        public Node(int data) {
            this.value = data;
        }
    }

    public static class DoubleNode {
        public int value;
        public DoubleNode last;
        public DoubleNode next;

        public DoubleNode(int data) {
            this.value = data;
        }
    }


    public static Node reverseLinkedList(Node head) {
        Node pre = null;
        Node next = null;

        while (head != null) {
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }

        return pre;
    }

    public static DoubleNode reverseDoubleLinkedList(DoubleNode head) {

        DoubleNode pre = null;
        DoubleNode next = null;

        while (head != null) {
            next = head.next;
            head.next = pre;
            head.last = next;
            pre = head;
            head = next;
        }
        return pre;
    }

    public static void main(String[] args) {
        Node node = new Node(1);
        node.next = new Node(2);
        node.next.next = new Node(3);
        node = reverse(node);
        while (node != null) {
            System.out.println(node.value);
            node = node.next;
        }

        System.out.println("=============================");
        DoubleNode doubleNodeHead = new DoubleNode(1);
        DoubleNode doubleNode1 = new DoubleNode(2);
        doubleNodeHead.next = doubleNode1;
        doubleNode1.last = doubleNodeHead;

        DoubleNode doubleNode2 = new DoubleNode(3);

        doubleNode1.next = doubleNode2;
        doubleNode2.last = doubleNode1;
        doubleNodeHead = reverseDoubleNode(doubleNodeHead);
        while (doubleNodeHead != null) {
            System.out.println(doubleNodeHead.value);
            doubleNodeHead = doubleNodeHead.next;
        }


    }


    public static Node reverse(Node head) {
        Node pre = null, next = null;

        while (head != null) {
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;

        }
        return pre;
    }

    public static DoubleNode reverseDoubleNode(DoubleNode head) {
        DoubleNode pre = null, next = null;
        while (head != null) {
            next = head.next;
            head.next = pre;
            head.last = next;
            pre = head;
            head = next;
        }
        return pre;
    }
}
